package com.lxb.store.service.Impl;

import com.lxb.store.dao.GoodsDao;
import com.lxb.store.dao.UserDao;
import com.lxb.store.entity.Goods;
import com.lxb.store.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService{

   @Autowired
   private GoodsDao goodsDao;

    @Override
    public Page<Goods> findAll(Pageable pageable) {
        return goodsDao.findAll(pageable);
    }

    @Override
    public Goods getByID(Integer id) {
        return goodsDao.getById(id);
    }

    @Override
    public List<Goods> listGoodsTop(Integer size) {

        Sort  sort= Sort.by(Sort.Direction.DESC,"recommend");
        Pageable pageable = PageRequest.of(0,size,sort);

        return goodsDao.findTop(pageable);
    }

    @Override
    public Page<Goods> searchGoods(Pageable pageable, String goodsname) {

        return  goodsDao.findAll(new Specification<Goods>() {
            @Override
            public Predicate toPredicate(Root<Goods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                Predicate predicate = criteriaBuilder.like(root.get("goodsName"),"%"+goodsname+"%");

                return predicate;
            }
        },pageable);


    }
}
